package com.alcatel.axs.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;


import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alcatel.axs.model.ServerStatus;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class ClusterManagerUtils {
    private final static Logger m_logger = LoggerFactory.getLogger(ClusterManagerUtils.class);
      
    public static List<String> getClusterStatus(String ip, String username, String password) {

        JSch jsch = new JSch();
        List<String> output = null;
        try {
            // get connection
            Session session = jsch.getSession(username, ip);
            session.setPassword(password);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            m_logger.debug("Connecting...");
            // session.setServerAliveInterval(500);
            session.connect(30000);
            
            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");

            InputStream in = channelExec.getInputStream();
            // exec command
            channelExec.setCommand("./bin/ams_cluster status");
            channelExec.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            // get result
            output = IOUtils.readLines(reader);
            // Disconnect
            channelExec.disconnect();
            //get line 4 to check type: cluter or simplex
            if(output.get(4).endsWith("Standalone")) {
                // 
                ChannelExec channelExec2 = (ChannelExec) session.openChannel("exec");
                channelExec2 = (ChannelExec) session.openChannel("exec");
                in = channelExec2.getInputStream();
                channelExec2.setCommand("./bin/ams_server status");
                channelExec2.connect();
                reader = new BufferedReader(new InputStreamReader(in));
                output = IOUtils.readLines(reader);
            }
            
            
            session.disconnect();
        } catch (JSchException e) {
            m_logger.debug(e.getMessage(), e);
        } catch (Exception e) {
            m_logger.debug(e.getMessage(), e);
        }
        return output;
    }
    
    public static List<String> excuteCommand(String ip, String username, String password, String command) {

        JSch jsch = new JSch();
        List<String> output = null;
        try {
            // get connection
            Session session = jsch.getSession(username, ip);
            session.setPassword(password);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            m_logger.debug("Connecting...");
            // session.setServerAliveInterval(500);
            session.connect(30000);
            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");

            InputStream in = channelExec.getInputStream();
            // exec command
            String request = "./bin/ams_server "+command;
            channelExec.setCommand(request);
            channelExec.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            // get result
            output = IOUtils.readLines(reader);
            // Disconnect
            channelExec.disconnect();
            session.disconnect();
        } catch (JSchException e) {
            m_logger.debug(e.getMessage(), e);
        } catch (Exception e) {
            m_logger.debug(e.getMessage(), e);
        }
        return output;
    }
    
    public static String getServerStatus(List<String> result, String ip) {
        String status="";
        int index = 1;
        List<String> tmp;
        for (String s:result) {
            if(s.startsWith("Cluster IP:")) {
                tmp= parseContent(s.substring(s.indexOf(":")+1));
                index = tmp.indexOf(ip);
            }
            if(s.startsWith("Server status:")) {
                tmp= parseContent(s.substring(s.indexOf(":")+1));
                if(tmp.get(index).contains("Healthy")) {
                    status = ServerStatus.HEALTHY.toString();
                }else if(tmp.get(index).contains("Degraded")){
                    status = ServerStatus.DEGRADED.toString();
                }
                break;
            }
            status = ServerStatus.DOWN.toString();
        }
        return status;
    }
    
    private static List<String> parseContent(String lineContent) {
        return Arrays.asList(lineContent.split("\\s{1,}"));
    }
    
    public static void main(final String[] args) {
        List<String> result = getClusterStatus("192.168.95.29","amssys","amssys");
        for (String s : result) {
            System.out.println(s);
        }
    }
}
